#include "goboard.h"
#include <QtGlobal>
#include <QRandomGenerator>

GoBoard::GoBoard(QObject* parent) : QObject(parent) {
    connect(&m_logic, &GoLogic::boardChanged, this, &GoBoard::boardChanged);
    connect(&m_logic, &GoLogic::capturedChanged,
            this, [this](int b, int w) { m_black = b; m_white = w; emit capturedChanged(); });
    connect(&m_logic, &GoLogic::turnChanged, this, &GoBoard::onTurnChanged);
    connect(&m_logic, &GoLogic::turnChanged, this, &GoBoard::turnChanged);

    // 配置AI定时器
    m_aiTimer.setSingleShot(true);
    connect(&m_aiTimer, &QTimer::timeout, this, &GoBoard::makeAIMove);
}

QVector<int> GoBoard::boardData() const {
    auto bd = m_logic.boardData();
    QVector<int> v(bd.size());
    for (int i = 0; i < bd.size(); ++i) v[i] = static_cast<int>(bd[i]);
    return v;
}

bool GoBoard::playStone(int r, int c) {
    bool success = m_logic.playStone(r, c);
    // 玩家落子成功后，不需要手动触发AI，onTurnChanged会自动处理
    return success;
}

void GoBoard::onTurnChanged() {
    // 如果是AI模式且轮到白棋(AI)，触发AI落子
    if (m_logic.gameMode() == static_cast<int>(GameMode::AI) && !m_logic.isBlackTurn()) {
        // 延迟500ms让AI落子更自然
        m_aiTimer.start(500);
    }
}

void GoBoard::makeAIMove() {
    // 收集所有合法落子位置
    QVector<QPoint> validMoves;
    int size = m_logic.size();
    auto boardCopy = m_logic.boardData();

    for (int r = 0; r < size; ++r) {
        for (int c = 0; c < size; ++c) {
            // 只检查空位置
            if (boardCopy[r * size + c] == Color::Empty) {
                validMoves.append(QPoint(r, c));
            }
        }
    }

    // 从合法位置中随机选择一个
    if (!validMoves.isEmpty()) {
        int randomIndex = QRandomGenerator::global()->bounded(validMoves.size());
        QPoint move = validMoves[randomIndex];

        // AI尝试落子，如果失败则重试
        for (int attempt = 0; attempt < validMoves.size(); ++attempt) {
            if (m_logic.playStone(move.x(), move.y())) {
                break; // 成功落子
            }
            // 失败则选择下一个位置
            randomIndex = (randomIndex + 1) % validMoves.size();
            move = validMoves[randomIndex];
        }
    }
}
